import { useReducer } from "react";

// interface State 描述了 reducer state 的类型
interface State {
  count: number;
}

// type CounterAction 描述了可以 dispatch 至 reducer 的不同 action
type CounterAction =
  | { type: "reset" }
  | { type: "setCount"; value: State["count"] };

// const initialState: State 为初始 state 提供类型，并且也将成为 useReducer 默认使用的类型
const initialState: State = { count: 0 };

// stateReducer(state: State, action: CounterAction): State 设置了 reducer 函数参数和返回值的类型
function stateReducer(state: State, action: CounterAction): State {
  switch (action.type) {
    case "reset":
      return initialState;
    case "setCount":
      return { ...state, count: action.value };
    default:
      throw new Error("Unknow action");
  }
}

const Counter = () => {
  const [state, dispatch] = useReducer(stateReducer, initialState);

  const addFive = () => dispatch({ type: "setCount", value: state.count + 5 });

  const reset = () => dispatch({ type: "reset" });

  return (
    <div>
      <p>计数： {state.count}</p>
      <button onClick={addFive}>加 5</button>
      <button onClick={reset}>重置</button>
    </div>
  );
};

export default Counter;
